<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input v-model="queryParams.userName" class="list-input" placeholder="搜索用户名称" @input="handleSearchInput"
               @confirm="handleSearch"/>
        <uni-icons v-if="queryParams.userName" type="clear" size="16" color="#999" @click="handleClear"></uni-icons>
      </view>
      <view class="list-filter-btn" @click="toggleFilter">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </view>
    </view>

    <!-- 筛选抽屉 -->
    <uni-popup ref="filterPopup" type="right" :mask-click="false">
      <view class="list-filter-drawer">
        <view class="list-filter-header">
          <text class="list-filter-title">高级筛选</text>
          <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
        </view>
        <view class="list-filter-content">
          <view class="list-filter-item">
            <text class="list-filter-label">手机号码</text>
            <uni-easyinput v-model="queryParams.phonenumber" placeholder="请输入手机号码" :clearable="true"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">部门</text>
            <BottomSelect v-model="queryParams.deptId" :options="deptOptions" value-field="value" label-field="text"
                          placeholder="请选择部门" title="选择部门"/>
          </view>
        </view>
        <view class="list-filter-footer">
          <view class="btn btn-reset" @click="handleFilterReset">重置</view>
          <view class="btn btn-confirm" @click="handleFilterConfirm">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn" :class="isAllSelected ? 'btn-warning' : 'btn-default'" @click="handleSelectAll">
        <uni-icons :type="isAllSelected ? 'checkbox-filled' : 'checkbox'" size="14"
                   :color="isAllSelected ? '#ff9500' : '#666'"/>
        <text>{{ isAllSelected ? '取消全选' : '全选' }}</text>
      </view>
      <view class="btn btn-primary" :class="{ 'btn-disabled': selectedUsers.length === 0 }" @click="handleBatchAuth">
        <uni-icons type="checkmarkempty" size="14" color="#007aff"/>
        <text>授权({{ selectedUsers.length }})</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"/>
        <text>刷新</text>
      </view>
    </view>

    <!-- 用户列表 -->
    <view class="list-content">
      <view v-for="user in userList" :key="user.userId" class="list-item" :class="{ 'selected': isUserSelected(user) }"
            @click="handleUserSelect(user)">
        <view class="list-avatar">
          <uni-icons :type="isUserSelected(user) ? 'checkbox-filled' : 'checkbox'" size="24"
                     :color="isUserSelected(user) ? '#007aff' : '#d9d9d9'"></uni-icons>
        </view>
        <view class="list-info">
          <view class="list-header">
            <text class="list-title">{{ user.userName }}</text>
            <text class="list-subtitle">{{ user.nickName }}</text>
            <view class="status-badge" :class="user.status === '0' ? 'status-normal' : 'status-disabled'">
              {{ user.status === '0' ? '正常' : '停用' }}
            </view>
          </view>
          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="list" size="14" color="#999"/>
              <text class="detail-text">ID：{{ user.userId }}</text>
            </view>
            <view class="detail-item" v-if="user.phonenumber">
              <uni-icons type="phone" size="14" color="#999"/>
              <text class="detail-text">{{ user.phonenumber }}</text>
            </view>
            <view class="detail-item" v-if="user.email">
              <uni-icons type="email" size="14" color="#999"/>
              <text class="detail-text">{{ user.email }}</text>
            </view>
            <view class="detail-item" v-if="user.dept">
              <uni-icons type="home" size="14" color="#999"/>
              <text class="detail-text">{{ user.dept.deptName }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="calendar" size="14" color="#999"/>
              <text class="detail-text">{{ parseTime(user.createTime, '{y}-{m}-{d}') }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view v-if="!loading && userList.length === 0" class="list-empty">
      <uni-icons type="person" size="48" color="#ddd"/>
      <text class="list-empty-text">暂无可选择的用户</text>
    </view>

    <!-- 加载更多 -->
    <view v-if="userList.length > 0" class="list-load-more">
      <uni-load-more :status="loadStatus" :content-text="loadText"></uni-load-more>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {authUserSelectAll, unallocatedUserList} from '@/api/system/role'
import {listDept} from '@/api/system/dept'
import {parseTime} from '@/utils/ruoyi'
import {BottomSelect} from '@/components/select'

const {proxy} = getCurrentInstance()

// 页面参数
const roleId = ref(null)
const roleName = ref('')

// 数据定义
const userList = ref([])
const selectedUsers = ref([])
const total = ref(0)
const loading = ref(false)
const loadStatus = ref('more')
const filterPopup = ref(null)
let searchTimer = null

const loadText = reactive({
  contentdown: '上拉显示更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleId: null,
  userName: '',
  phonenumber: '',
  deptId: ''
})

// 部门选项
const deptOptions = ref([{value: '', text: '全部部门'}])

// 计算属性
const isAllSelected = computed(() => {
  return userList.value.length > 0 && selectedUsers.value.length === userList.value.length
})

// 页面初始化
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options

  roleId.value = Number(options.roleId)
  roleName.value = decodeURIComponent(options.roleName || '')
  queryParams.roleId = Number(options.roleId)

  // 获取部门列表和用户列表
  getDeptList()
  getList()
})

// 获取部门列表
async function getDeptList() {
  try {
    const response = await listDept()
    if (response.code === 200) {
      const deptList = (response.data || []).map(dept => ({
        value: dept.deptId,
        text: dept.deptName
      }))
      deptOptions.value = [{value: '', text: '全部部门'}, ...deptList]
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
  }
}

// 获取用户列表
async function getList() {
  if (loading.value) return

  loading.value = true
  loadStatus.value = 'loading'

  try {
    const response = await unallocatedUserList(queryParams)
    if (response.code === 200) {
      const newData = response.rows || []

      if (queryParams.pageNum === 1) {
        userList.value = newData
        selectedUsers.value = []
      } else {
        userList.value.push(...newData)
      }

      total.value = response.total || 0

      // 判断是否还有更多数据
      if (userList.value.length >= total.value) {
        loadStatus.value = 'noMore'
      } else {
        loadStatus.value = 'more'
      }
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    proxy.$modal.showToast('获取用户列表失败')
    loadStatus.value = 'more'
  } finally {
    loading.value = false
  }
}

// 筛选相关函数
function toggleFilter() {
  filterPopup.value.open()
}

function closeFilter() {
  filterPopup.value.close()
}

function handleFilterConfirm() {
  closeFilter();
  handleSearch()
}

function handleFilterReset() {
  Object.assign(queryParams, {phonenumber: '', deptId: ''})
}

// 搜索处理
function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleSearch()
  }, 300)
}

function handleSearch() {
  queryParams.pageNum = 1
  userList.value = []
  selectedUsers.value = []
  getList()
}

// 清空搜索
function handleClear() {
  queryParams.userName = ''
  handleSearch()
}

// 加载更多
function handleLoadMore() {
  if (loadStatus.value === 'more' && !loading.value) {
    queryParams.pageNum++
    getList()
  }
}

// 判断用户是否已选中
function isUserSelected(user) {
  return selectedUsers.value.some(u => u.userId === user.userId)
}

// 用户选择
function handleUserSelect(user) {
  const index = selectedUsers.value.findIndex(u => u.userId === user.userId)
  if (index > -1) {
    selectedUsers.value.splice(index, 1)
  } else {
    selectedUsers.value.push(user)
  }
}

// 全选/取消全选
function handleSelectAll() {
  if (isAllSelected.value) {
    selectedUsers.value = []
  } else {
    selectedUsers.value = [...userList.value]
  }
}

// 批量授权
async function handleBatchAuth() {
  if (selectedUsers.value.length === 0) {
    proxy.$modal.showToast('请选择要授权的用户')
    return
  }

  const result = await proxy.$modal.confirm(`确认要将"${roleName.value}"角色授权给选中的${selectedUsers.value.length}个用户吗？`)
  if (result) {
    try {
      const userIds = selectedUsers.value.map(user => user.userId).join(',')
      const response = await authUserSelectAll({
        roleId: roleId.value,
        userIds: userIds
      })

      if (response.code === 200) {
        proxy.$modal.showToast('授权成功')
        setTimeout(() => {
          handleBack()
        }, 1500)
      } else {
        proxy.$modal.showToast(response.msg || '授权失败')
      }
    } catch (error) {
      console.error('授权失败:', error)
      proxy.$modal.showToast('授权失败')
    }
  }
}

// 刷新
function handleRefresh() {
  queryParams.pageNum = 1
  userList.value = []
  selectedUsers.value = []
  getList()
}

// 返回
function handleBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import '@/styles/list-page.scss';

// 选中状态样式
.list-item.selected {
  background: #f0f8ff;
  border-left: 4px solid #007aff;
}

// 禁用按钮样式
.btn-disabled {
  opacity: 0.5;
  pointer-events: none;
}
</style>